const express = require('express');
const router = express.Router();
// const crypto = require('crypto');
const sqlQuery = require('../lcSql');
const jiami = require('../md5');

// 获取注册页面
router.get('/', (req, res) => {
    res.render('register');
});

// 处理注册请求
router.post('/', async (req, res) => {
    let username = req.body.username;
    let password = req.body.password;

    // 构造查询语句
    let sqlStr = "SELECT username FROM users WHERE username = ?";
    let result = await sqlQuery(sqlStr, [username]);

    // 检查用户名是否已存在
    if (result.length > 0) {
        // 用户名已存在
        res.json({ status: 'error', message: '此用户已注册，可直接登录，或找回密码', redirect: '/login'  });
    } else {
        // 用户名不存在，插入新用户
        let sqlStr = "INSERT INTO users (username, password) VALUES (?, ?)";
        let encryptedPassword = jiami.md5(password + jiami.salt);
        await sqlQuery(sqlStr, [username, encryptedPassword]);
        res.json({ status: 'success', message: '注册成功，即将进入登录页面', redirect: '/login' });
    }
});

module.exports = router;
